import React, { useState, useEffect, useRef } from "react";
import {
  Layout,
  Card,
  List,
  Input,
  Button,
  Avatar,
  message,
  Spin,
  Empty,
  Space,
  Typography,
  Tag,
  Divider,
  Badge,
  ConfigProvider,
  Row,
  Col,
} from "antd";
import {
  MessageOutlined,
  SendOutlined,
  UserOutlined,
  RobotOutlined,
  CloseOutlined,
  ReloadOutlined,
  SearchOutlined,
  WifiOutlined,
  DisconnectOutlined,
} from "@ant-design/icons";
import { getAllUsers } from "../api/users";
import {
  sendUserChatMessage,
  getChatHistory,
  getQueueStatus,
  joinQueue,
  leaveQueue,
  createChatWebSocket,
  sendHeartbeat,
} from "../api/userChat";
import { useTheme } from "../contexts/ThemeContext";

const { Content } = Layout;
const { TextArea } = Input;
const { Text, Title } = Typography;

export default function UserChat() {
  const { isDarkMode } = useTheme();

  // 用户相关状态
  const [users, setUsers] = useState([]);
  const [filteredUsers, setFilteredUsers] = useState([]);
  const [searchKeyword, setSearchKeyword] = useState("");
  const [selectedUser, setSelectedUser] = useState(null);
  const [currentUserId, setCurrentUserId] = useState(null);
  const [currentUsername, setCurrentUsername] = useState(null);

  // 聊天相关状态
  const [chatMessages, setChatMessages] = useState([]);
  const [currentMessage, setCurrentMessage] = useState("");
  const [chatLoading, setChatLoading] = useState(false);
  const [historyLoading, setHistoryLoading] = useState(false);

  // WebSocket相关状态（保留但不使用）
  const [ws, setWs] = useState(null);
  const [isConnected, setIsConnected] = useState(false);
  const [onlineUsers, setOnlineUsers] = useState([]);
  const [queueCount, setQueueCount] = useState(0);

  // UI状态
  const [usersLoading, setUsersLoading] = useState(false);
  const [queueLoading, setQueueLoading] = useState(false);

  // refs
  const chatMessagesEndRef = useRef(null);
  const heartbeatIntervalRef = useRef(null);
  const historyPollRef = useRef(null); // 用于在 websocket 不可用时轮询历史记录
  const lastMessageAtRef = useRef(null); // 记录最后一条消息的时间戳，便于增量拉取
  const selectedUserRef = useRef(null);
  const currentUserIdRef = useRef(null);

  // 初始化当前用户信息
  useEffect(() => {
    const userId = localStorage.getItem("userId");
    const username = localStorage.getItem("username");
    if (userId && username) {
      setCurrentUserId(userId);
      setCurrentUsername(username);
    }
  }, []);

  // 获取用户列表
  const loadUsers = async () => {
    setUsersLoading(true);
    try {
      const response = await getAllUsers(); // 获取所有用户
      const userList = response.list || response || [];
      // 过滤掉当前用户
      const otherUsers = userList.filter(
        (user) => user.id !== parseInt(currentUserId)
      );
      setUsers(otherUsers);
      setFilteredUsers(sortUsersByOnlineStatus(otherUsers)); // 初始化时排序
    } catch (error) {
      console.error("获取用户列表失败:", error);
      message.error("获取用户列表失败");
    } finally {
      setUsersLoading(false);
    }
  };

  // 搜索用户
  const handleSearchUsers = (value) => {
    setSearchKeyword(value);
    if (!value.trim()) {
      setFilteredUsers(sortUsersByOnlineStatus(users));
    } else {
      const filtered = users.filter(
        (user) =>
          user.name.toLowerCase().includes(value.toLowerCase()) ||
          user.id.toString().includes(value)
      );
      setFilteredUsers(sortUsersByOnlineStatus(filtered));
    }
  };

  // 根据在线状态排序用户
  const sortUsersByOnlineStatus = (userList) => {
    return [...userList].sort((a, b) => {
      const aOnline = isUserOnline(a.id);
      const bOnline = isUserOnline(b.id);

      // 在线用户排在前面
      if (aOnline && !bOnline) return -1;
      if (!aOnline && bOnline) return 1;

      // 都在线或都不在线的情况下，按用户ID排序
      return a.id - b.id;
    });
  };

  // 获取队列状态
  const loadQueueStatus = async () => {
    setQueueLoading(true);
    try {
      const response = await getQueueStatus();
      if (response.code === 1 && response.data) {
        setOnlineUsers(response.data.onlineUsers || []);
        setQueueCount(response.data.count || 0);
      }
    } catch (error) {
      console.error("获取队列状态失败:", error);
    } finally {
      setQueueLoading(false);
    }
  };

  // 加载聊天历史
  const loadChatHistory = async (otherId, isPoll = false) => {
    if (!currentUserId || !otherId) return;

    console.log(
      `[loadChatHistory] start. otherId=${otherId}, isPoll=${isPoll}, time=${new Date().toISOString()}`
    );
    setHistoryLoading(true);
    try {
      // 构造请求体，添加 _t 用于避免缓存（Proxy / CDN / 浏览器）
      const payload = {
        userId: currentUserId,
        otherId: otherId.toString(),
        page: 1,
        size: 100,
        _t: Date.now(), // 缓存破坏参数，确保每次请求都到后端
      };

      const response = await getChatHistory(payload);

      console.log("获取聊天历史响应:", response);

      // 处理新的响应结构
      let messages = [];
      if (response.code === 1 && response.data && response.data.messages) {
        messages = response.data.messages;
      }

      console.log("解析后的消息列表:", messages);

      if (messages && messages.length > 0) {
        // 按时间升序
        messages.sort((a, b) => new Date(a.createdAt) - new Date(b.createdAt));

        if (isPoll) {
          // 轮询时只追加比 lastMessageAtRef 更晚的消息
          const lastAt = lastMessageAtRef.current
            ? new Date(lastMessageAtRef.current)
            : null;
          const newMsgs = messages.filter((m) => {
            try {
              return !lastAt || new Date(m.createdAt) > lastAt;
            } catch (e) {
              return true;
            }
          });

          if (newMsgs.length > 0) {
            const mappedNew = newMsgs.map((msg) => ({
              id: msg.id || `msg_${Date.now()}_${Math.random()}`,
              senderId: msg.senderId,
              receiverId: msg.receiverId,
              content: msg.content,
              timestamp: new Date(msg.createdAt),
              type: msg.senderId === currentUserId ? "sent" : "received",
            }));

            setChatMessages((prev) => {
              // 去重：避免重复追加相同 id
              const existingIds = new Set(prev.map((m) => m.id));
              const filtered = mappedNew.filter((m) => !existingIds.has(m.id));
              if (filtered.length === 0) return prev;
              return [...prev, ...filtered];
            });
          }
        } else {
          // 非轮询调用，直接替换为最新历史
          const formattedMessages = messages.map((msg) => ({
            id: msg.id || `msg_${Date.now()}_${Math.random()}`,
            senderId: msg.senderId,
            receiverId: msg.receiverId,
            content: msg.content,
            timestamp: new Date(msg.createdAt),
            type: msg.senderId === currentUserId ? "sent" : "received",
          }));
          setChatMessages(formattedMessages);
        }

        // 更新 lastMessageAtRef 为当前拉取到的最新消息时间
        try {
          const latest = messages[messages.length - 1].createdAt;
          lastMessageAtRef.current = latest;
          console.log(
            `[loadChatHistory] update lastMessageAtRef=${lastMessageAtRef.current}`
          );
        } catch (e) {
          // ignore
        }
      } else {
        // 没有消息时，如果是非轮询调用要清空
        if (!isPoll) setChatMessages([]);
      }
    } catch (error) {
      console.error("获取聊天历史失败:", error);
      // 轮询情况下避免频繁弹窗
      if (!isPoll) message.error("获取聊天历史失败");
      if (!isPoll) setChatMessages([]);
    } finally {
      setHistoryLoading(false);
      console.log(
        `[loadChatHistory] end. otherId=${otherId}, isPoll=${isPoll}, time=${new Date().toISOString()}`
      );
    }
  };

  // 自动滚动到聊天消息底部
  const scrollToBottom = () => {
    chatMessagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [chatMessages]);

  // 选择聊天用户
  const handleSelectUser = async (user) => {
    setSelectedUser(user);
    await loadChatHistory(user.id);
  };

  // 手动加入队列（建立WebSocket连接但发送消息用HTTP）
  const handleJoinQueue = async () => {
    if (!currentUserId || !currentUsername) {
      message.error("用户信息不完整");
      return;
    }

    if (isConnected) {
      message.info("已经在聊天队列中");
      return;
    }

    try {
      // 先调用手动加入队列接口
      const response = await joinQueue({
        userId: currentUserId,
        username: currentUsername,
      });

      if (response.code === 1) {
        // 建立WebSocket连接用于接收消息
        const websocket = createChatWebSocket(
          currentUserId,
          // onMessage - 处理接收到的消息
          (wsMessage) => {
            console.log("收到WebSocket消息:", wsMessage);

            if (wsMessage.type === "message") {
              // 添加接收到的消息
              const newMessage = {
                id: `ws_${Date.now()}_${Math.random()}`,
                senderId: wsMessage.senderId,
                receiverId: wsMessage.receiverId,
                content: wsMessage.content,
                timestamp: new Date(wsMessage.timestamp || Date.now()),
                type: "received",
              };
              setChatMessages((prev) => [...prev, newMessage]);
            } else if (wsMessage.type === "pong") {
              console.log("收到心跳回复");
            } else if (wsMessage.type === "system") {
              message.info(wsMessage.content);
            }
          },
          // onOpen
          () => {
            setIsConnected(true);
            message.success("已加入聊天队列并建立实时连接");
            loadQueueStatus();

            // WebSocket连接成功，停止历史轮询
            stopHistoryPolling();

            // 启动心跳
            if (heartbeatIntervalRef.current) {
              clearInterval(heartbeatIntervalRef.current);
            }
            heartbeatIntervalRef.current = setInterval(() => {
              sendHeartbeat(websocket);
            }, 30000); // 30秒发送一次心跳
          },
          // onClose
          () => {
            setIsConnected(false);
            console.log("WebSocket连接已断开，可点击重连按钮恢复实时接收");

            // WebSocket断开，如果有选中用户就启动历史轮询
            if (selectedUserRef.current && currentUserIdRef.current) {
              startHistoryPolling();
            }

            // 清除心跳
            if (heartbeatIntervalRef.current) {
              clearInterval(heartbeatIntervalRef.current);
              heartbeatIntervalRef.current = null;
            }
          },
          // onError
          (error) => {
            console.error("WebSocket连接错误:", error);
            message.error("WebSocket连接失败，但仍可发送消息");
            setIsConnected(false);

            // WebSocket错误，如果有选中用户就启动历史轮询
            if (selectedUserRef.current && currentUserIdRef.current) {
              startHistoryPolling();
            }
          }
        );

        setWs(websocket);

        // 如果 WebSocket 未能创建（可能后端不可达），则启动历史轮询以保证仍能获取新消息
        if (!websocket) {
          console.warn("WebSocket 未创建，启动历史轮询");
          if (selectedUser && currentUserId) {
            startHistoryPolling();
          }
        }
      } else {
        message.error(`加入队列失败: ${response.message || "未知错误"}`);
      }
    } catch (error) {
      console.error("加入队列失败:", error);
      message.error("加入聊天队列失败");
    }
  };

  // 重连WebSocket
  const handleReconnectWebSocket = async () => {
    if (isConnected) {
      message.info("WebSocket连接正常，无需重连");
      return;
    }

    if (!currentUserId || !currentUsername) {
      message.error("用户信息不完整");
      return;
    }

    try {
      message.loading("正在重连WebSocket...", 1);

      // 先关闭现有连接
      if (ws) {
        ws.close();
        setWs(null);
      }

      // 等待一下再重连
      await new Promise((resolve) => setTimeout(resolve, 1000));

      // 重新建立WebSocket连接
      const websocket = createChatWebSocket(
        currentUserId,
        // onMessage - 处理接收到的消息
        (wsMessage) => {
          console.log("收到WebSocket消息:", wsMessage);

          if (wsMessage.type === "message") {
            // 添加接收到的消息
            const newMessage = {
              id: `ws_${Date.now()}_${Math.random()}`,
              senderId: wsMessage.senderId,
              receiverId: wsMessage.receiverId,
              content: wsMessage.content,
              timestamp: new Date(wsMessage.timestamp || Date.now()),
              type: "received",
            };
            setChatMessages((prev) => [...prev, newMessage]);
          } else if (wsMessage.type === "pong") {
            console.log("收到心跳回复");
          } else if (wsMessage.type === "system") {
            message.info(wsMessage.content);
          }
        },
        // onOpen
        () => {
          setIsConnected(true);
          message.success("WebSocket重连成功");
          loadQueueStatus();

          // WebSocket重连成功，停止历史轮询
          stopHistoryPolling();

          // 启动心跳
          if (heartbeatIntervalRef.current) {
            clearInterval(heartbeatIntervalRef.current);
          }
          heartbeatIntervalRef.current = setInterval(() => {
            sendHeartbeat(websocket);
          }, 30000); // 30秒发送一次心跳
        },
        // onClose
        () => {
          setIsConnected(false);
          console.log("WebSocket连接已断开，可点击重连按钮恢复实时接收");

          // WebSocket断开，如果有选中用户就启动历史轮询
          if (selectedUserRef.current && currentUserIdRef.current) {
            startHistoryPolling();
          }

          // 清除心跳
          if (heartbeatIntervalRef.current) {
            clearInterval(heartbeatIntervalRef.current);
            heartbeatIntervalRef.current = null;
          }
        },
        // onError
        (error) => {
          console.error("WebSocket重连错误:", error);
          message.error("WebSocket重连失败");
          setIsConnected(false);

          // WebSocket重连错误，如果有选中用户就启动历史轮询
          if (selectedUserRef.current && currentUserIdRef.current) {
            startHistoryPolling();
          }
        }
      );

      setWs(websocket);
    } catch (error) {
      console.error("WebSocket重连失败:", error);
      message.error("WebSocket重连失败");
    }
  };

  // 手动离开队列
  const handleLeaveQueue = async () => {
    if (!currentUserId) {
      message.error("用户信息不完整");
      return;
    }

    try {
      // 关闭WebSocket连接
      if (ws) {
        ws.close();
        setWs(null);
      }

      // 调用离开队列接口
      const response = await leaveQueue({
        userId: currentUserId,
      });

      if (response.code === 1) {
        setIsConnected(false);
        message.success("已离开聊天队列");
        setQueueCount(0);
        setOnlineUsers([]);

        // 清除心跳和历史轮询
        if (heartbeatIntervalRef.current) {
          clearInterval(heartbeatIntervalRef.current);
          heartbeatIntervalRef.current = null;
        }
        stopHistoryPolling();
      } else {
        message.error(`离开队列失败: ${response.message || "未知错误"}`);
      }
    } catch (error) {
      console.error("离开队列失败:", error);
      message.error("离开聊天队列失败");
    }
  };

  // 发送消息 (HTTP方式)
  const handleSendMessage = async () => {
    console.log("handleSendMessage 被调用");
    console.log("当前状态:", {
      currentMessage: currentMessage.trim(),
      selectedUser: selectedUser?.name,
      currentUserId,
      chatLoading,
    });

    if (!currentMessage.trim()) {
      message.warning("请输入消息内容");
      return;
    }

    if (!selectedUser) {
      message.warning("请选择聊天用户");
      return;
    }

    const messageData = {
      senderId: currentUserId,
      receiverId: selectedUser.id.toString(),
      content: currentMessage.trim(),
    };

    console.log("准备发送消息:", messageData);

    // 使用HTTP接口发送
    setChatLoading(true);
    try {
      console.log("开始调用 sendUserChatMessage API");
      const response = await sendUserChatMessage(messageData);
      console.log("HTTP发送响应:", response);

      // 更宽松的成功判断条件
      if (response && response.code === 1) {
        console.log("消息发送成功，添加到聊天记录");
        // 立即添加发送的消息到聊天记录
        const sentMessage = {
          id: response.data?.messageId || `http_${Date.now()}_${Math.random()}`,
          senderId: currentUserId,
          receiverId: selectedUser.id.toString(),
          content: currentMessage.trim(),
          timestamp: new Date(),
          type: "sent",
        };
        setChatMessages((prev) => [...prev, sentMessage]);
        setCurrentMessage("");
        message.success("消息发送成功");
      } else {
        console.error("发送失败，响应:", response);
        message.error(
          `发送失败: ${response?.msg || response?.message || "服务器响应异常"}`
        );

        // 即使服务器返回错误，也尝试添加到本地显示（用户体验）
        console.log("服务器返回错误，但仍添加到本地显示");
        const sentMessage = {
          id: `http_${Date.now()}_${Math.random()}`,
          senderId: currentUserId,
          receiverId: selectedUser.id.toString(),
          content: currentMessage.trim(),
          timestamp: new Date(),
          type: "sent",
        };
        setChatMessages((prev) => [...prev, sentMessage]);
        setCurrentMessage("");
      }
    } catch (error) {
      console.error("发送消息网络错误:", error);
      message.error("发送消息失败: " + (error.message || "网络错误"));

      // 网络错误时也添加到本地显示
      console.log("网络错误，但仍添加到本地显示");
      const sentMessage = {
        id: `http_${Date.now()}_${Math.random()}`,
        senderId: currentUserId,
        receiverId: selectedUser.id.toString(),
        content: currentMessage.trim(),
        timestamp: new Date(),
        type: "sent",
      };
      setChatMessages((prev) => [...prev, sentMessage]);
      setCurrentMessage("");
    } finally {
      setChatLoading(false);
      console.log("发送消息流程结束");
    }
  };

  // 处理Enter键发送消息
  const handleKeyPress = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  // 监听用户列表和在线状态变化，更新过滤结果
  useEffect(() => {
    handleSearchUsers(searchKeyword);
  }, [users, onlineUsers]);

  // 启动/停止历史轮询的函数
  const startHistoryPolling = () => {
    if (!historyPollRef.current) {
      console.log(`[historyPoll] start polling at ${new Date().toISOString()}`);
      historyPollRef.current = setInterval(() => {
        const su = selectedUserRef.current;
        const cu = currentUserIdRef.current;
        if (su && cu) {
          console.log(
            `[historyPoll] polling for selectedUser=${su.id}, currentUser=${cu}`
          );
          loadChatHistory(su.id, true);
        } else {
          console.log(
            "[historyPoll] skipping poll - no selectedUser or no currentUserId"
          );
        }
      }, 2000);
    }
  };

  const stopHistoryPolling = () => {
    if (historyPollRef.current) {
      console.log(`[historyPoll] stop polling at ${new Date().toISOString()}`);
      clearInterval(historyPollRef.current);
      historyPollRef.current = null;
    }
  };

  // keep refs in sync with state so interval callbacks see latest value
  useEffect(() => {
    selectedUserRef.current = selectedUser;
  }, [selectedUser]);

  useEffect(() => {
    currentUserIdRef.current = currentUserId;
  }, [currentUserId]);

  // 监控连接状态和选中用户，决定是否需要轮询
  useEffect(() => {
    if (!isConnected && selectedUser && currentUserId) {
      // WebSocket未连接且有选中用户时，启动轮询
      startHistoryPolling();
    } else {
      // WebSocket已连接或没有选中用户时，停止轮询
      stopHistoryPolling();
    }
  }, [isConnected, selectedUser, currentUserId]);

  // 组件挂载时的初始化
  useEffect(() => {
    if (currentUserId) {
      loadUsers();
      loadQueueStatus();

      // 自动建立WebSocket连接
      const timer = setTimeout(() => {
        if (!isConnected && currentUserId && currentUsername) {
          console.log("自动建立WebSocket连接");
          handleJoinQueue();
        }
      }, 1000); // 延迟1秒确保用户信息已设置

      return () => clearTimeout(timer);
    }
  }, [currentUserId, currentUsername, isConnected]);

  // 页面关闭时自动离开队列
  useEffect(() => {
    const handleBeforeUnload = () => {
      if (ws) {
        ws.close();
      }
    };

    window.addEventListener("beforeunload", handleBeforeUnload);

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, [ws]);

  // 定期刷新队列状态
  useEffect(() => {
    const interval = setInterval(() => {
      if (isConnected) {
        loadQueueStatus();
      }
    }, 10000); // 每10秒刷新一次

    return () => clearInterval(interval);
  }, [isConnected]);

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (ws) {
        ws.close();
      }
      if (heartbeatIntervalRef.current) {
        clearInterval(heartbeatIntervalRef.current);
      }
      stopHistoryPolling();
    };
  }, []);

  // 定期刷新队列状态
  useEffect(() => {
    const interval = setInterval(() => {
      if (isConnected) {
        loadQueueStatus();
      }
    }, 10000); // 每10秒刷新一次

    return () => clearInterval(interval);
  }, [isConnected]);

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (ws) {
        ws.close();
      }
      if (heartbeatIntervalRef.current) {
        clearInterval(heartbeatIntervalRef.current);
      }
      if (historyPollRef.current) {
        clearInterval(historyPollRef.current);
      }
    };
  }, [ws]);

  // 判断用户是否在线
  const isUserOnline = (userId) => {
    return onlineUsers.includes(userId.toString());
  };

  return (
    <>
      {/* 全局滚动条样式 */}
      <style>
        {`
          .user-list-scroll {
            scrollbar-width: thin;
            scrollbar-color: ${
              isDarkMode ? "#434343 #1f1f1f" : "#c1c1c1 #f1f1f1"
            };
          }
          .user-list-scroll::-webkit-scrollbar {
            width: 8px;
          }
          .user-list-scroll::-webkit-scrollbar-track {
            background: ${isDarkMode ? "#1f1f1f" : "#f1f1f1"};
            border-radius: 4px;
          }
          .user-list-scroll::-webkit-scrollbar-thumb {
            background: ${isDarkMode ? "#434343" : "#c1c1c1"};
            border-radius: 4px;
          }
          .user-list-scroll::-webkit-scrollbar-thumb:hover {
            background: ${isDarkMode ? "#555" : "#a8a8a8"};
          }
          .user-list-item {
            border-bottom: 1px solid ${
              isDarkMode ? "#434343" : "#f5f5f5"
            } !important;
          }
          .user-list-item:last-child {
            border-bottom: none !important;
          }
          /* 确保 flexbox 容器不会溢出 */
          .ant-row {
            overflow: hidden;
          }
          .ant-col {
            overflow: hidden;
          }
        `}
      </style>
      <ConfigProvider
        theme={{
          token: {
            colorBgBase: isDarkMode ? "#141414" : "#ffffff",
            colorTextBase: isDarkMode ? "#ffffff" : "#000000",
          },
        }}
        modal={{
          contentBgColor: isDarkMode ? "#141414" : "#ffffff",
          titleColor: isDarkMode ? "#ffffff" : "#000000",
          colorBgMask: isDarkMode
            ? "rgba(0, 0, 0, 0.85)"
            : "rgba(0, 0, 0, 0.45)",
        }}
        message={{
          token: {
            colorBgDefault: isDarkMode ? "#262626" : "#ffffff",
            colorTextBase: isDarkMode ? "#ffffff" : "#000000",
            colorBorder: isDarkMode ? "#434343" : "#d9d9d9",
          },
        }}
        notification={{
          token: {
            colorBgDefault: isDarkMode ? "#262626" : "#ffffff",
            colorTextBase: isDarkMode ? "#ffffff" : "#000000",
            colorBorder: isDarkMode ? "#434343" : "#d9d9d9",
          },
        }}>
        <div
          style={{
            padding: "24px",
            background: isDarkMode ? "#141414" : "#f5f5f5",
            height: "100vh",
            overflow: "hidden", // 防止页面级别滚动
            display: "flex",
            flexDirection: "column",
          }}>
          {/* 页面标题 */}
          <div style={{ textAlign: "center", marginBottom: 24, flexShrink: 0 }}>
            <Title level={2} style={{ color: "#1890ff", marginBottom: 8 }}>
              <MessageOutlined /> 用户聊天
            </Title>
            <Text
              type="secondary"
              style={{
                fontSize: 16,
                color: isDarkMode ? "#888" : "#666",
                transition: "color 0.3s ease",
              }}>
              基于Gin WebSocket的实时在线聊天交流
            </Text>
          </div>

          <Row gutter={[24, 24]} style={{ flex: 1, minHeight: 0 }}>
            {/* 左侧用户列表 */}
            <Col
              xs={24}
              md={8}
              lg={6}
              style={{ height: "100%", display: "flex" }}>
              <Card
                title={
                  <Space>
                    <UserOutlined />
                    <span>用户列表</span>
                    <Badge
                      count={queueCount}
                      showZero
                      color="#52c41a"
                      title="在线用户数"
                    />
                  </Space>
                }
                extra={
                  <Space>
                    <Button
                      size="small"
                      icon={<ReloadOutlined />}
                      onClick={loadUsers}
                      loading={usersLoading}
                      title="刷新用户列表"
                    />
                  </Space>
                }
                style={{
                  height: "100%",
                  width: "100%",
                  background: isDarkMode ? "#1f1f1f" : "#fff",
                  display: "flex",
                  flexDirection: "column",
                }}
                styles={{
                  body: {
                    padding: 0,
                    flex: 1,
                    overflow: "hidden",
                    display: "flex",
                    flexDirection: "column",
                  },
                }}>
                <div
                  style={{
                    padding: "12px 16px",
                    borderBottom: `1px solid ${
                      isDarkMode ? "#434343" : "#f0f0f0"
                    }`,
                    flexShrink: 0, // 防止压缩
                  }}>
                  <div style={{ marginBottom: 12 }}>
                    <Space>
                      <Tag color={isConnected ? "green" : "red"}>
                        {isConnected ? (
                          <>
                            <WifiOutlined /> 已连接队列
                          </>
                        ) : (
                          <>
                            <DisconnectOutlined /> 未连接队列
                          </>
                        )}
                      </Tag>
                      {!isConnected && (
                        <Button
                          size="small"
                          type="primary"
                          icon={<WifiOutlined />}
                          onClick={handleReconnectWebSocket}
                          title="重新连接WebSocket">
                          重连
                        </Button>
                      )}
                    </Space>
                    <div style={{ marginTop: 8 }}>
                      <Text type="secondary" style={{ fontSize: 12 }}>
                        在线: {queueCount}人
                      </Text>
                    </div>
                  </div>
                  <Input
                    placeholder="搜索用户名或ID..."
                    prefix={<SearchOutlined />}
                    value={searchKeyword}
                    onChange={(e) => handleSearchUsers(e.target.value)}
                    allowClear
                    size="small"
                    style={{
                      background: isDarkMode ? "#2a2a2a" : "#fff",
                      borderColor: isDarkMode ? "#434343" : "#d9d9d9",
                    }}
                  />
                </div>

                <div
                  className="user-list-scroll"
                  style={{
                    flex: 1, // 占据剩余空间
                    overflow: "auto",
                    overflowX: "hidden", // 隐藏横向滚动条
                  }}>
                  <Spin spinning={usersLoading}>
                    {filteredUsers.length === 0 ? (
                      <Empty
                        description={
                          searchKeyword ? "未找到匹配用户" : "暂无其他用户"
                        }
                        style={{ marginTop: 40 }}
                      />
                    ) : (
                      <List
                        dataSource={filteredUsers}
                        split={false} // 移除默认分割线，使用自定义样式
                        size="small" // 使用小尺寸减少空间占用
                        renderItem={(user) => (
                          <List.Item
                            key={user.id}
                            className="user-list-item"
                            onClick={() => handleSelectUser(user)}
                            style={{
                              cursor: "pointer",
                              backgroundColor:
                                selectedUser?.id === user.id
                                  ? isDarkMode
                                    ? "#1f4e79"
                                    : "#e6f7ff"
                                  : "transparent",
                              borderLeft:
                                selectedUser?.id === user.id
                                  ? "3px solid #1890ff"
                                  : "3px solid transparent",
                              padding: "6px 12px", // 进一步减小padding
                              margin: 0,
                              transition: "all 0.2s",
                              minHeight: "auto", // 移除最小高度限制
                            }}
                            onMouseEnter={(e) => {
                              if (selectedUser?.id !== user.id) {
                                e.currentTarget.style.backgroundColor =
                                  isDarkMode ? "#2a2a2a" : "#f9f9f9";
                              }
                            }}
                            onMouseLeave={(e) => {
                              if (selectedUser?.id !== user.id) {
                                e.currentTarget.style.backgroundColor =
                                  "transparent";
                              }
                            }}>
                            <List.Item.Meta
                              avatar={
                                user.img ? (
                                  <Avatar src={user.img} size={32} />
                                ) : (
                                  <Avatar icon={<UserOutlined />} size={32} />
                                )
                              }
                              title={
                                <div
                                  style={{
                                    fontSize: 13, // 稍微减小字体
                                    display: "flex",
                                    alignItems: "center",
                                    justifyContent: "space-between",
                                    lineHeight: "1.2", // 减小行高
                                  }}>
                                  <span
                                    style={{
                                      color: isDarkMode ? "#fff" : "#333",
                                      overflow: "hidden", // 防止长名字溢出
                                      textOverflow: "ellipsis",
                                      whiteSpace: "nowrap",
                                      maxWidth: "120px", // 限制最大宽度
                                    }}>
                                    {user.name}
                                  </span>
                                  {isUserOnline(user.id) && (
                                    <Tag
                                      color="green"
                                      size="small"
                                      style={{
                                        marginLeft: 4,
                                        fontSize: 10,
                                        padding: "0 4px", // 减小标签padding
                                        lineHeight: "14px", // 减小标签高度
                                      }}>
                                      在线
                                    </Tag>
                                  )}
                                </div>
                              }
                              description={
                                <Text type="secondary" style={{ fontSize: 10 }}>
                                  ID: {user.id}
                                </Text>
                              }
                            />
                          </List.Item>
                        )}
                      />
                    )}
                  </Spin>
                </div>
              </Card>
            </Col>

            {/* 右侧聊天区域 */}
            <Col
              xs={24}
              md={16}
              lg={18}
              style={{ height: "100%", display: "flex" }}>
              <Card
                title={
                  selectedUser ? (
                    <Space>
                      <MessageOutlined />
                      <span>与 {selectedUser.name} 聊天</span>
                    </Space>
                  ) : (
                    <Space>
                      <MessageOutlined />
                      <span>选择用户开始聊天</span>
                    </Space>
                  )
                }
                extra={
                  selectedUser && (
                    <Button
                      size="small"
                      icon={<CloseOutlined />}
                      onClick={() => {
                        setSelectedUser(null);
                        setChatMessages([]);
                      }}>
                      关闭
                    </Button>
                  )
                }
                style={{
                  height: "100%",
                  width: "100%",
                  background: isDarkMode ? "#1f1f1f" : "#fff",
                  display: "flex",
                  flexDirection: "column",
                }}
                styles={{
                  body: {
                    padding: 0,
                    flex: 1,
                    overflow: "hidden",
                    display: "flex",
                    flexDirection: "column",
                  },
                }}>
                {!selectedUser ? (
                  <div
                    style={{
                      height: "100%",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      color: isDarkMode ? "#888" : "#999",
                    }}>
                    <div style={{ textAlign: "center" }}>
                      <MessageOutlined
                        style={{ fontSize: 48, marginBottom: 16 }}
                      />
                      <div>请从左侧选择一个用户开始聊天</div>
                    </div>
                  </div>
                ) : (
                  <>
                    {/* 聊天消息区域 */}
                    <div
                      style={{
                        flex: 1, // 占据剩余空间
                        overflow: "auto",
                        padding: "16px",
                        background: isDarkMode ? "#262626" : "#fafafa",
                      }}>
                      <Spin spinning={historyLoading}>
                        {chatMessages.length === 0 ? (
                          <div
                            style={{
                              textAlign: "center",
                              color: isDarkMode ? "#888" : "#999",
                              padding: "40px 20px",
                            }}>
                            <RobotOutlined
                              style={{ fontSize: 48, marginBottom: 16 }}
                            />
                            <div>暂无聊天记录，发送第一条消息开始对话吧！</div>
                          </div>
                        ) : (
                          chatMessages.map((msg) => (
                            <div
                              key={msg.id}
                              style={{
                                marginBottom: 16,
                                display: "flex",
                                justifyContent:
                                  msg.type === "sent"
                                    ? "flex-end"
                                    : "flex-start",
                              }}>
                              <div
                                style={{
                                  maxWidth: "70%",
                                  padding: "8px 12px",
                                  borderRadius: "12px",
                                  backgroundColor:
                                    msg.type === "sent"
                                      ? "#1890ff"
                                      : isDarkMode
                                      ? "#434343"
                                      : "#fff",
                                  color:
                                    msg.type === "sent"
                                      ? "#fff"
                                      : isDarkMode
                                      ? "#fff"
                                      : "#333",
                                  boxShadow: isDarkMode
                                    ? "0 1px 2px rgba(0,0,0,0.3)"
                                    : "0 1px 2px rgba(0,0,0,0.1)",
                                  wordBreak: "break-word",
                                }}>
                                <div>{msg.content}</div>
                                <div
                                  style={{
                                    fontSize: "12px",
                                    marginTop: "4px",
                                    opacity: 0.7,
                                    textAlign:
                                      msg.type === "sent" ? "right" : "left",
                                  }}>
                                  {msg.timestamp.toLocaleTimeString()}
                                </div>
                              </div>
                            </div>
                          ))
                        )}
                        <div ref={chatMessagesEndRef} />
                      </Spin>
                    </div>

                    {/* 输入区域 */}
                    <div
                      style={{
                        flexShrink: 0, // 防止压缩
                        padding: "16px",
                        borderTop: `1px solid ${
                          isDarkMode ? "#434343" : "#f0f0f0"
                        }`,
                        background: isDarkMode ? "#1f1f1f" : "#fff",
                      }}>
                      <div style={{ display: "flex", gap: "8px" }}>
                        <TextArea
                          value={currentMessage}
                          onChange={(e) => setCurrentMessage(e.target.value)}
                          onKeyPress={handleKeyPress}
                          placeholder={`发送消息给 ${selectedUser.name}...`}
                          autoSize={{ minRows: 1, maxRows: 4 }}
                          style={{ flex: 1 }}
                          disabled={chatLoading}
                        />
                        <Button
                          type="primary"
                          icon={<SendOutlined />}
                          onClick={handleSendMessage}
                          loading={chatLoading}
                          disabled={!currentMessage.trim()}
                          title="发送消息">
                          发送
                        </Button>
                      </div>
                      <div
                        style={{
                          fontSize: "12px",
                          color: isDarkMode ? "#888" : "#999",
                          marginTop: "8px",
                          display: "flex",
                          alignItems: "center",
                          justifyContent: "space-between",
                        }}>
                        <span>
                          按 Enter 发送，Shift + Enter 换行 •{" "}
                          {isConnected ? (
                            <span style={{ color: "#52c41a" }}>
                              实时连接已建立
                            </span>
                          ) : (
                            <span style={{ color: "#ff4d4f" }}>
                              实时连接未建立
                            </span>
                          )}
                        </span>
                        {!isConnected && (
                          <Button
                            size="small"
                            type="link"
                            icon={<WifiOutlined />}
                            onClick={handleReconnectWebSocket}
                            style={{
                              padding: "0 4px",
                              height: "auto",
                              fontSize: "12px",
                              color: "#1890ff",
                            }}>
                            重连
                          </Button>
                        )}
                      </div>
                    </div>
                  </>
                )}
              </Card>
            </Col>
          </Row>
        </div>
      </ConfigProvider>
    </>
  );
}
